package com.hm.pan.aop;

import javax.servlet.http.HttpServletRequest;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import com.hm.pan.model.ResultObj;
import com.hm.pan.model.User;

@Aspect
@Component
public class LoginAOP {

	// 拦截被com.hm.pan.annotation.CheckLogin注解的类的所有方法。其中标记了com.hm.pan.annotation.NoLogin的不拦截
	@Pointcut("@within(com.hm.pan.annotation.CheckLogin) && !@annotation(com.hm.pan.annotation.NoLogin)")
	public void checkLogin() {
	}

	@Around("com.hm.pan.aop.LoginAOP.checkLogin()")
	public Object xxx(ProceedingJoinPoint pjp) throws Throwable {
		// 获取session中的用户信息
		HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes())
				.getRequest();
		User user = (User) request.getSession().getAttribute("user");

		if (user == null) {
			ResultObj resultObj = new ResultObj();
			resultObj.setStatusCode(401);
			resultObj.setMessage("Unauthorized");
			return resultObj;
		}

		Object[] args = pjp.getArgs();
		return pjp.proceed(args);
	}
}
